package service

import (
	"context"
	"mall-admin-go/dao"
	"mall-admin-go/model"
	"mall-admin-go/pkg/e"
	"mall-admin-go/pkg/util"
	"mall-admin-go/serializer"
)

type UserService struct {
	UserName  string `form:"username"`
	NickName  string `form:"nickname"`
	Status    string `form:"status"`
	Mobile    string `form:"mobile"`
	CreatedAt int64  `form:"create"`
	model.BasePage
}

func (service *UserService) ListUser(ctx context.Context) interface{} {
	userDao := dao.NewUserDao(ctx)
	if service.PageNum == 0 || service.PageNum < 1 {
		service.PageNum = 1
	}
	if service.PageSize > 15 {
		service.PageNum = 15
	}
	//筛选条件
	conditions := make(map[string]interface{})
	if service.UserName != "" {
		conditions["user_name"] = service.UserName
	}
	if service.NickName != "" {
		conditions["nick_name"] = service.NickName
	}
	if service.Mobile != "" {
		conditions["mobile"] = service.Mobile
	}
	if service.Status != "" {
		conditions["status"] = service.Status
	}
	if service.CreatedAt != 0 {
		StartDay, EndDay := util.GetDateDay(service.CreatedAt)
		userList, total, err := userDao.GetAllUserByDate(conditions, service.BasePage, StartDay, EndDay)
		//	试了好多方法都不行还是用多种查询吧
		if err != nil {
			return serializer.ErrorResponse(e.Error)
		}
		return serializer.BuildListResponse(serializer.BuildUsers(userList), uint(total), service.PageNum, service.PageSize)
	}
	userList, total, err := userDao.GetAllUser(conditions, service.BasePage)
	if err != nil {
		return serializer.ErrorResponse(e.Error)
	}

	return serializer.BuildListResponse(serializer.BuildUsers(userList), uint(total), service.PageNum, service.PageSize)
}

func (service *UserService) InfoUser(uid string, ctx context.Context) interface{} {
	if uid == "" {
		return serializer.ErrorResponse(e.InvalidParams)
	}
	userDao := dao.NewUserDao(ctx)
	user, err := userDao.GetUserByUid(uid)
	if err != nil {
		return serializer.ErrorResponse(e.ErrorExistUserNotFound)
	}
	return serializer.SuccessResponse(serializer.BuildUser(user))
}
